package org.cars.decoder;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.util.CharsetUtil;

import java.util.List;

public class StringLineDelimiterDecoder extends ByteToMessageDecoder {
    public static final byte SEPARATOR = (byte) '\n';

    @Override
    protected void decode(ChannelHandlerContext context, ByteBuf byteBuf, List<Object> out) throws Exception {
        int delimiterIndex = byteBuf.indexOf(byteBuf.readerIndex(), byteBuf.writerIndex(), SEPARATOR);

        //当前接收到的数据没有包含分隔符, 证明数据包不完整, 等待后续的数据
        if (delimiterIndex == -1) {
            return;
        }
        ByteBuf sliceBuf = byteBuf.readSlice(delimiterIndex - byteBuf.readerIndex() + 1);
        String message = sliceBuf.toString(CharsetUtil.UTF_8);

        out.add(message);
    }
}